package com.lcc.myblog.service.impl;

import com.lcc.lynx.common.cache.service.CacheService;
import com.lcc.lynx.common.utils.DateUtil;
import com.lcc.myblog.constant.WorkBillStateConst;
import com.lcc.myblog.pojo.dv.BkWorkBillDV;
import com.lcc.myblog.pojo.dv.BkWorkBillDtlDV;
import com.lcc.myblog.service.BkWorkBillDtlService;
import com.lcc.myblog.service.BkWorkBillService;
import com.lcc.myblog.mapper.BkWorkBillMapper;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * 工单管理服务实现
 * @auth lcc
 * @date 2025-03-21
 */
@Service
@Transactional
@AllArgsConstructor
public class BkWorkBillServiceImpl implements BkWorkBillService {

    private BkWorkBillMapper mapper;

    private BkWorkBillDtlService workBillDtlService;

    private CacheService cacheService;

    @Override
    public int insert(BkWorkBillDV bkWorkBillDV) {
        bkWorkBillDV.setBillNo(getNextBillNo(bkWorkBillDV));
        bkWorkBillDV.setBillState(WorkBillStateConst.NEW);
        BkWorkBillService.super.insert(bkWorkBillDV);
        BkWorkBillDtlDV bkWorkBillDtlDV = new BkWorkBillDtlDV();
        bkWorkBillDtlDV.setBillId(bkWorkBillDV.getBillId());
        bkWorkBillDtlDV.setContent("空空如也");
        workBillDtlService.insert(bkWorkBillDtlDV);
        return 1;
    }

    @Override
    public int delete(BkWorkBillDV bkWorkBillDV) {
        BkWorkBillService.super.delete(bkWorkBillDV);
        workBillDtlService.deleteById(bkWorkBillDV.getBillId());
        return 1;
    }

    private String getNextBillNo(BkWorkBillDV bkWorkBillDV) {
        String billNo = "NM" + bkWorkBillDV.getBillType() + DateUtil.getDate_yyyyMM();
        String seqKey = "bill_seq:" + billNo;
        long no;
        if(cacheService.contains(seqKey)){
            no = cacheService.increment(seqKey, 1);
        }else{
            Long max = mapper.getMaxMonthNumber(bkWorkBillDV.getBillType());
            if(max==null){
                max = 0L;
            }
            no = cacheService.increment(seqKey, max + 1);
            // 缓存一个月
            cacheService.expire(seqKey, 31, TimeUnit.DAYS);
        }
        bkWorkBillDV.setMonthNumber((int) no);
        return billNo + String.format("%04d", no);
    }

    @Override
    public BkWorkBillMapper getMapper() {
       return mapper;
    }

}